﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.Net;
using System.Net.Sockets;
using eLibCommon;

namespace eLibClient
{
  public partial class Form1 : Form
  {
    private TcpClient _internalClient;
    private TcpListener _internalReceiver;
    private string _serverIP = "192.168.1.33";
    private int _helloPort = 13000;

    public delegate void AppendTextDelegate(string myString);
    private AppendTextDelegate appender;

    public Form1()
    {
      InitializeComponent();

      _internalReceiver = new TcpListener(new IPEndPoint(IPAddress.Any, 13001));
      _internalReceiver.Start();
      _internalReceiver.BeginAcceptTcpClient(new AsyncCallback(this.ReceiveCallback), null);

      this.appender = new AppendTextDelegate(TextAppender);  
    }

    private void btnConnect_Click(object sender, EventArgs e)
    {
      _serverIP = txtServerIP.Text;
      int.TryParse(txtServerPort.Text, out _helloPort);

      if (_internalClient == null)
        _internalClient = new TcpClient(_serverIP, _helloPort);

      TcpUtils.SendText(_internalClient, "HELLO");
    }
    


    private void ReceiveCallback(IAsyncResult ar)
    {
      TcpClient client = _internalReceiver.EndAcceptTcpClient(ar);
      string receiveString = TcpUtils.ReceiveText(client);
      textBox1.Invoke(appender, new Object[] { receiveString });
    }

    private void TextAppender(string text)
    {
      textBox1.AppendText(text);
    }
  }
}
